<!--二级集团环保检查计划制定 /checkPlan-->
<template>
  <Layout>
    <Form ref="queryForm" :model="dataToQuery" :label-width="120">
      <Row v-show="!switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="所属二级集团：">
            <Select class='w' placeholder="请选择" v-model='dataToQuery.twoLevelOrgId'>
              <Option v-for="item in twoLevel" :value="item.orgId" :key="item.orgId">{{ item.orgName }}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label='计划年月：'>
            <DatePicker class="w" type="month"
                        :transfer="true" placeholder="请选择计划年月"
                        v-model='dataToQuery.planMonth'
                        @on-change="setPlanDate"></DatePicker>
          </FormItem>
        </Col>
        <Col span="8">
          <!--          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>-->
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="所属二级集团：">
            <Select class='w' placeholder="请选择" v-model='dataToQuery.twoLevelOrgId'>
              <Option v-for="item in twoLevel" :value="item.orgId" :key="item.orgId">{{ item.orgName }}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label='计划年月：' prop='planDate'>
            <DatePicker class="w" type="month" :transfer="true" placeholder="请选择计划年月"
                        v-model='dataToQuery.planDate'></DatePicker>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label='计划主题：' prop='planTitle'>
            <Input type='text' v-model='dataToQuery.planTitle'></Input>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8" offset="16">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>

    </Form>
    <Row :gutter="14" style="margin-top: 15px">
      <Col span="12">
        <Card dis-hover>
          <p class="p-title">▎ </p>
          <p>计划与实际检查对比图</p>
          <div ref="planToMonth" :style="{height: height+'px'}"></div>
        </Card>
      </Col>
      <Col span="12">
        <Card dis-hover>
          <p class="p-title">▎ </p>
          <p>二级集团检查计划与实际检查对比图</p>
          <div ref="planToOrg" :style="{height: height+'px'}"></div>
        </Card>
      </Col>
    </Row>
    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
           :loading='pageStatus.loading'
           border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
      </Col>
    </Row>
  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import {sessionStorage} from '@/common/cacheUtils.js';
import pageCommonFunction from '@/components/pageCommonFunction.js'
import echarts from "echarts";

var cascaderDom = () => import('@/components/cascader-dom.vue');

export default {
  components: {
    cascaderDom
  },
  data() {
    return {
      ...this.createCommonDataField(),
      height: 170,
      options: {
        disabledDate(date) {
          let dateNow = new Date();
          return date && date.valueOf() < dateNow.setMonth(dateNow.getMonth() - 1);
        }
      },
      columns1: [
        {title: '序号', width: 80, fixed: 'left', align: 'center', render: this.indexColumnsRender},
        {key: 'companyName', title: '检查单位', align: 'center', minWidth: 120},
        {key: 'inspectorsName', title: '计划参检人员', align: 'center', minWidth: 120},
        {key: 'checkTime', title: '计划检查时间', align: 'center', minWidth: 120, render: this.renderCellDate},
        {key: 'inspectionTime', title: '实际检查时间', align: 'center', minWidth: 120, render: this.renderCellDate},
        {key: 'rummager', title: '实际检查人员', align: 'center', minWidth: 120},
        {key: 'issueCount', title: '问题数量', align: 'center', minWidth: 120},
      ],
      ruleCustom: {
        twoLevelOrgId: [{required: true, message: '请填写所属二级集团', trigger: 'change',}],
        planTitle: [{required: true, message: '请填写检查计划主题', trigger: 'change',}],
        planDate: [{required: true, message: '请填写计划年月', trigger: 'change', type: 'date'}],
      },
      planType: this.$route.query.planType,
      twoLevel: [],
      tableHeight: 10,
      // api
      queryUrl: Api.queryCheckPlanStatistics,
      deleteUrl: Api.deleteCheckPlanUrl,
      updateUrl: Api.updateCheckPlanUrl,
      saveUrl: Api.saveCheckPlanUrl,

      findPlanToMonth: Api.findPlanToMonth,
      findPlanToOrg: Api.findPlanToOrg,
    }
  },

  mounted() {
    this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
      this.twoLevel = res.data.data
    })
    this.$set(this.dataToQuery, 'planMonth', this.renderViewMonth(new Date()))
    // this.tableHeight = 250
    this.setTableHeight();
    this.query();

  },
  methods: {
    ...pageCommonFunction,
    getPlantToMonth() {
      let _this = this;
      let container = echarts.init(this.$refs.planToMonth);
      this.$http.get(this.findPlanToMonth + "/" + this.planType, {params:this.dataToQuery}).then(res => {
        if (res.data.status === 201) {
          this.$Message.error(res.data.msg);
        }
        if (res.data.status === 200) {

          let planData = _this.convertMon(res.data.data);
          let option = _this.getPlantToMonthOption(planData);
          container.setOption(option);

        }
        window.onresize = container.resize;
      }).catch(e => {
        console.log(e)
        this.$Message.error("查询失败")
      });
    },
    convertMon(data) {
      let obj = {
        plan: [],
        actual: [],
        month: [],
      }
      data.forEach(item => {
        obj.plan.push(item.planNum);
        obj.month.push(item.month);
        obj.actual.push(item.actual);
      });

      return obj;

    },
    convertOrg(data) {
      let obj = {
        plan: [],
        actual: [],
        orgNames: [],
      }
      data.forEach(item => {
        obj.plan.push(item.planNum);
        obj.orgNames.push(item.orgName);
        obj.actual.push(item.actual);
      });

      return obj;

    },
    getPlanToOrg() {
      let _this = this;
      let container = echarts.init(this.$refs.planToOrg);
      this.$http.get(this.findPlanToOrg + "/" + this.planType, {params:this.dataToQuery}).then(res => {
        if (res.data.status === 201) {
          this.$Message.error(res.data.msg);
        }
        if (res.data.status === 200) {

          let planData = _this.convertOrg(res.data.data);
          let option = _this.getPlanToOrgOption(planData);
          container.setOption(option)
        }
        window.onresize = container.resize;
      }).catch(e => {
        console.log(e)
        this.$Message.error("查询失败")
      });

    },
    getPlantToMonthOption(data) {
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['计划', '实际']
        },
        toolbox: {
          show: true,
          orient: 'vertical',
          left: 'right',
          top: 'center',

        },
        xAxis: [
          {
            type: 'category',
            axisTick: {show: false},
            data: data.month,
            axisLabel: {
              show: true,
              interval: 0,
              formatter: function (params) {
                var newParamsName = "";
                var paramsNameNumber = params.length;
                var provideNumber = 3; // 一行显示几个字 然后就超过字数就会自动换行
                var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
                if (paramsNameNumber > provideNumber) {
                  for (var p = 0; p < rowNumber; p++) {
                    var tempStr = "";
                    var start = p * provideNumber;
                    var end = start + provideNumber;
                    if (p == rowNumber - 1) {
                      tempStr = params.substring(start, paramsNameNumber);
                    } else {
                      tempStr = params.substring(start, end) + "\n";
                    }
                    newParamsName += tempStr;
                  }
                } else {
                  newParamsName = params;
                }
                return newParamsName + "月";
              },
            },
          }
        ],
        yAxis: [
          {
            type: 'value',

          }
        ],
        color: ['#42A5F5', '#FFC310'],
        series: [
          {
            name: '计划',
            type: 'bar',
            // barWidth : 30,
            barGap: "1%",
            label: {
              show: true,

            },
            itemStyle: {
              barBorderRadius: [4, 4, 0, 0],
            },
            data: data.plan,

          },
          {
            name: '实际',
            type: 'line',
            barGap: "1%",
            smooth: true,
            label: {
              show: true,

            },
            // barWidth: 30,
            itemStyle: {
              barBorderRadius: [4, 4, 0, 0],
            },

            data: data.actual,
          },

        ]
      }
    },
    getPlanToOrgOption(data) {
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['计划', '实际']
        },
        toolbox: {
          show: true,
          orient: 'vertical',
          left: 'right',
          top: 'center',

        },
        xAxis: [
          {
            type: 'category',
            axisTick: {show: false},
            data: data.orgNames,
            axisLabel: {
              show: true,
              interval: 0,
              formatter: function (params) {
                var newParamsName = "";
                var paramsNameNumber = params.length;
                var provideNumber = 3; // 一行显示几个字 然后就超过字数就会自动换行
                var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
                if (paramsNameNumber > provideNumber) {
                  for (var p = 0; p < rowNumber; p++) {
                    var tempStr = "";
                    var start = p * provideNumber;
                    var end = start + provideNumber;
                    if (p == rowNumber - 1) {
                      tempStr = params.substring(start, paramsNameNumber);
                    } else {
                      tempStr = params.substring(start, end) + "\n";
                    }
                    newParamsName += tempStr;
                  }
                } else {
                  newParamsName = params;
                }
                return newParamsName;
              },
            },
          }
        ],
        yAxis: [
          {
            type: 'value',

          }
        ],
        color: ['#42A5F5', '#FFC310'],
        series: [
          {
            name: '计划',
            type: 'bar',
            // barWidth : 30,
            barGap: "1%",
            label: {
              show: true,

            },
            itemStyle: {
              barBorderRadius: [4, 4, 0, 0],
            },
            data: data.plan,

          },
          {
            name: '实际',
            type: 'bar',
            barGap: "1%",
            label: {
              show: true,

            },
            // barWidth: 30,
            itemStyle: {
              barBorderRadius: [4, 4, 0, 0],
            },

            data: data.actual,
          },

        ]
      }
    },
    comparedDate(date) {
      let nowDate = new Date();
      let planDate = new Date(date);
      //当前年份大于 计划年份
      if (nowDate.getFullYear() > planDate.getFullYear()) {
        return true;
      } else if (nowDate.getFullYear() === planDate.getFullYear()) {
        let nowMonth = nowDate.getMonth() + 1;
        let planDateMonth = planDate.getMonth() + 1;
        return nowMonth > planDateMonth;
      } else {
        return false;
      }
    },
    deleteData(params) {
      this.deleteDateAjax(params);
    },

    query() {
      this.dataToQuery.planType = this.planType;
      this.getPlantToMonth();
      this.getPlanToOrg();
      this.queryAjax();
    },
    submit(name) {
      this.submitAjax(name);
    },
    setPlanDate(date) {
      this.$set(this.dataToQuery, 'planMonth', this.renderViewMonth(date))
    },
    getNextM() { //获取下个月第一天
      let nowDate = new Date();
      return nowDate.getFullYear() + "-" + (parseInt(nowDate.getMonth() + 2) < 10 ? "0" + parseInt(nowDate.getMonth() + 2) : parseInt(nowDate.getMonth() + 2)) + "-01";
    },
    createEmptyDataToAdd() {
      return {
        planType: this.planType,
        twoLevelOrgId: sessionStorage('userId').getObject('userId').twoLevelOrgId,
        planDate: this.getNextM()
      }
    }
  },
  watch: {},

}
</script>

<style lang='css' scoped>

p {
  display: inline-block;
  font-size: 18px;
}

.p-title {
  display: inline-block;
  line-height: 27px;
  font-size: 18px;
  height: 27px;
  color: red;
}
</style>
